package com.twu.biblioteca.option;

import com.twu.biblioteca.BibliotecaApp;
import com.twu.biblioteca.core.Option;
import com.twu.biblioteca.core.User;
import com.twu.biblioteca.service.UserService;
import com.twu.biblioteca.util.Cli;

public class LoginOption extends Option {
    private UserService userService;
    private final BibliotecaApp app;

    public LoginOption(UserService userService, Cli cli, BibliotecaApp app) {
        super("Login", cli);
        this.userService = userService;
        this.app = app;
    }

    public boolean isAlreadyLogin() {
        return app.isAlreadyLogin();
    }

    public boolean login(String username, String password) {
        User user = new User(username, password);
        if (userService.checkUser(user)) {
            app.setCurrentUser(user);
        }
        return isAlreadyLogin();
    }

    @Override
    public void execute() {
        String username = cli.prompt("username:");
        String password = cli.prompt("password:");
        User user = new User(username, password);
        if (login(user)) {
            cli.output("success login");
        } else {
            cli.output("failed login");
        }
    }

    public boolean login(User user) {
        return login(user.getName(), user.getPassword());
    }
}
